﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using umbraco.cms.businesslogic;
using umbraco.BasePages;
using Core.Module;
using Core.Module.Interfaces.Model;
using Core.Module.Interfaces;
using Core.Module.Interfaces.Controller;
using Core.Module.Interfaces.Manager;

namespace Module.MultiSiteFields.DataServices
{
   public class TreeNodeInfoService:IHttpHandler
   {

       public bool IsReusable
       {
           get { return false; }
       }

       

       public void ProcessRequest(HttpContext context)
       {
           Authorize();
           context.Response.ContentType = "application/json";
           INodeController<IBackOffice> NodeManager = GetNodeController(TreeAlias);
           try
           {
               if ("-1".Equals(nodeid)) return;

               IModuleNode cnode = (NodeManager != null && !string.IsNullOrEmpty(nodeid)) ? NodeManager.Get(nodeid) : null;               
               context.Response.Write(cnode == null ? "" : Context.ToJson(cnode));
           }
           catch (ArgumentException aex)
           {
               context.Response.Write(aex.ToJson());
           }
       }

       private INodeController<IBackOffice> GetNodeController(string TreeAlias)
       {
           return ObjectManager.Resolve<INodeController<IBackOffice>>(TreeAlias.ToLowerInvariant());
       }



       #region internal methods
       public int NodeID
       {
           get
           {
               int num;
               if (int.TryParse(nodeid, out num))
                   return num;
               return -1;
           }
       }

       public string nodeid
       {
           get { return (HttpContext.Current.Request.QueryString["data"] ?? "").Trim(); }
       }
       public string TreeAlias
       {
           get
           {
               return HttpContext.Current.Request.QueryString["type"] ?? "";
           }
       }
      
       public static void Authorize()
       {
           if (!BasePage.ValidateUserContextID(BasePage.umbracoUserContextID))
           {
               throw new Exception("Client authorization failed. User is not logged in");
           }
       }
       #endregion
   }
}
